package com.bianguo.android.functiondemo.view.activity;

import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;

import com.bianguo.android.functiondemo.R;
import com.bianguo.android.functiondemo.utils.MLog;

import java.io.IOException;

import butterknife.BindView;

public class MediaPlayerActivity extends BaseActivity implements SurfaceHolder.Callback, MediaPlayer.OnVideoSizeChangedListener {

    @BindView(R.id.media_player_surface)
    SurfaceView mSurfaceView;
    @BindView(R.id.media_player_cover_img)
    ImageView coverImg;

//    private final String VIDEO_URL = "https://media.w3.org/2010/05/sintel/trailer.mp4";
    private final String VIDEO_URL = "http://fzb.feizhitong.cn/fzb/data/upload/video/2019-03-19/5c9088462e5bb.mp4";
    private SurfaceHolder mSurfaceViewHolder;
    private MediaPlayer currentPlayer, nextPlayer;
    private int surfaceWidth, surfaceHeight;

    @Override
    public int layoutId() {
        return R.layout.activity_media_player;
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        mSurfaceViewHolder = mSurfaceView.getHolder();
        mSurfaceViewHolder.addCallback(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlayer();
    }

    private void initPlayer() {
        MLog.mLog("initPlayer");
        currentPlayer = new MediaPlayer();
        try {
            currentPlayer.setDataSource(VIDEO_URL);
            currentPlayer.prepareAsync();
//            MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
//            mediaMetadataRetriever.setDataSource(VIDEO_URL);
//            int duration = currentPlayer.getDuration();
//            for (int i = 10000 * 1000; i < 20 * 1000 * 1000; i += 500 * 1000) {
//                MLog.mLog("i = " + i);
//                Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(i, MediaMetadataRetriever.OPTION_CLOSEST);
//                String path = CacheUtil.CACHE_DIR_TEMP_IMG + i + ".png";
//                FileOutputStream fileOutputStream = null;
//                try {
//                    fileOutputStream = new FileOutputStream(path);
//                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                } finally {
//                    if (fileOutputStream != null) {
//                        fileOutputStream.close();
//                    }
//                }
//                bitmap.recycle();
//            }
//            currentPlayer.setSurface(mSurfaceViewHolder.getSurface());
            currentPlayer.setDisplay(mSurfaceViewHolder);
            currentPlayer.setOnVideoSizeChangedListener(this);
            currentPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    int duration = mediaPlayer.getDuration();
                    MLog.mLog("video onPrepared duration = " + duration);
                    hideView(coverImg);
                    mediaPlayer.start();
                }
            });
            currentPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    MLog.mLog("video onCompletion");
                    mediaPlayer.release();
//                    currentPlayer = nextPlayer;
//                    createNextMediaPlayer();
                }
            });
//            createNextMediaPlayer();
        } catch (IOException e) {
            e.printStackTrace();
            MLog.mLog("error : " + e.getMessage());
        }
    }

    private void createNextMediaPlayer() {
        nextPlayer = new MediaPlayer();
        try {
            nextPlayer.setDataSource(VIDEO_URL);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopPlayer() {
        if (currentPlayer != null && currentPlayer.isPlaying()) {
            currentPlayer.stop();
            currentPlayer.release();
            currentPlayer = null;
        }
    }

    private void changeVideoSize() {
        int videoWidth = currentPlayer.getVideoWidth();
        int videoHeight = currentPlayer.getVideoHeight();

        //根据视频尺寸去计算->视频可以在sufaceView中放大的最大倍数。
        float max;
        if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            //竖屏模式下按视频宽度计算放大倍数值
            max = Math.max((float) videoWidth / (float) surfaceWidth, (float) videoHeight / (float) surfaceHeight);
        } else {
            //横屏模式下按视频高度计算放大倍数值
            max = Math.max(((float) videoWidth / (float) surfaceHeight), (float) videoHeight / (float) surfaceWidth);
        }

        //视频宽高分别/最大倍数值 计算出放大后的视频尺寸
        videoWidth = (int) Math.ceil((float) videoWidth / max);
        videoHeight = (int) Math.ceil((float) videoHeight / max);

        //无法直接设置视频尺寸，将计算出的视频尺寸设置到surfaceView 让视频自动填充。
        mSurfaceView.setLayoutParams(new ConstraintLayout.LayoutParams(videoWidth, videoHeight));
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        mSurfaceViewHolder = surfaceHolder;
        if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            surfaceWidth = mSurfaceView.getWidth();
            surfaceHeight = mSurfaceView.getHeight();
        } else {
            surfaceWidth = mSurfaceView.getHeight();
            surfaceHeight = mSurfaceView.getWidth();
        }
        initPlayer();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mSurfaceViewHolder = null;
        stopPlayer();
    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) {
        changeVideoSize();
    }
}
